<script setup lang="ts">
  import { computed, PropType, ref } from 'vue'
  import CheckGoodModal from '../good-list/CheckGoodModal.vue'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import LogisticsFillInModal from '../logistics-list/LogisticsFillInModal.vue'
  import SignForReceipt from '../logistics-list/SignForReceipt.vue'
  import { ElMessageBox } from 'element-plus'
  import { cancelReturnFactoryById } from '@/api/return-factory'
  import { useRoute, useRouter } from 'vue-router'
  import { useTagsViewStore } from '@/store/modules/tagsView'

  defineOptions({
    name: 'ReturnFactoryDetailHeader',
  })

  const props = defineProps({
    selectedGoods: {
      type: Array as PropType<Array<ReturnFactoryDetailGood>>,
      default: () => [],
    },
    moduleCheckMethod: {
      type: Number as PropType<1 | 2>,
      default: () => 2,
    },
    detail: {
      type: Object as PropType<ReturnFactoryDetail>,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  // 页面标签状态管理
  const tagsViewStore = useTagsViewStore()

  // 激活路由对象
  const route = useRoute()

  // 全局路由对象
  const router = useRouter()

  // 设备审核弹窗显示状态
  const goodCheckModalVisible = ref(false)

  // 物流填写弹窗显示状态
  const logisticsFillInModalVisible = ref(false)

  // 签收弹窗显示状态
  const signForReceiptModalVisible = ref(false)

  // 状态码对应的文本，用于页面显示和h-status组件的type属性的控制
  const statusTxt = computed<{ txt: string; status: 'warning' | 'primary' | 'success' | 'info' }>(
    () => {
      if (props.detail.status === 1) {
        return {
          txt: '待审核',
          status: 'warning',
        }
      }

      if (props.detail.status === 2) {
        return {
          txt: '待返厂',
          status: 'warning',
        }
      }

      if (props.detail.status === 3) {
        return {
          txt: '待签收',
          status: 'warning',
        }
      }

      if (props.detail.status === 4) {
        return {
          txt: '处理中',
          status: 'primary',
        }
      }

      if (props.detail.status === 5) {
        return {
          txt: '待寄回',
          status: 'warning',
        }
      }

      if (props.detail.status === 6) {
        return {
          txt: '待签收',
          status: 'warning',
        }
      }

      if (props.detail.status === 7) {
        return {
          txt: '已完成',
          status: 'success',
        }
      }

      return {
        txt: '已取消',
        status: 'info',
      }
    },
  )

  /**
   * 审核事件
   */
  const onCheck = async () => {
    if (props.moduleCheckMethod === 2 && props.selectedGoods.length <= 0) {
      HMessageBox.error('请选择设备')
      return
    }

    if (props.selectedGoods.some((item) => item.status !== 0)) {
      HMessageBox.error('只能选择待审核的设备')
      return
    }

    goodCheckModalVisible.value = true
  }

  /**
   * 填写物流点击事件
   */
  const onFillLogistics = async () => {
    if (props.moduleCheckMethod === 2 && props.selectedGoods.length === 0) {
      HMessageBox.error('请选择设备')
      return
    }

    if (props.selectedGoods.some((item) => item.status !== 1)) {
      HMessageBox.error('只能选择待返厂的设备')
      return
    }

    logisticsFillInModalVisible.value = true
  }

  /**
   * 签收设备事件
   */
  const onSignForReceipt = async () => {
    if (props.moduleCheckMethod === 2 && props.selectedGoods.length === 0) {
      HMessageBox.error('请选择设备')
      return
    }

    if (props.selectedGoods.some((item) => item.status !== 2)) {
      HMessageBox.error('只能选择待签收的设备')
      return
    }

    signForReceiptModalVisible.value = true
  }

  /**
   * 生成检测单
   */
  // const onDetectCreate = async () => {
  //   if (props.detail.status === 4 && props.selectedGoods.length <= 0) {
  //     HMessageBox.error(infoTip.returnFactory.detail.create_detect_good_is_empty)
  //     return
  //   }

  //   if (props.selectedGoods.some((item) => item.status !== 3)) {
  //     HMessageBox.error('只能选择待检测的设备')
  //     return
  //   }

  //   form.value.repairId = props.detail.id
  //   form.value.repairGoodsIds = props.selectedGoods.map((item) => item.id)
  //   const res = await create()
  //   if (res.code === 20000) {
  //     emits('update')
  //     HMessage.success(infoTip.returnFactory.detail.create_detect_success)
  //     return
  //   }

  //   HMessageBox.error(res.message)
  // }

  /**
   * 取消点击事件
   */
  const onCancelClick = () => {
    ElMessageBox({
      title: '提示',
      message: '确定要取消该返厂单？',
      autofocus: false,
      type: 'warning',
      showCancelButton: true,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      beforeClose(action, instance, done) {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.cancelButtonLoading = true
          cancelReturnFactoryById(props.detail.id)
            .then((res) => {
              if (res.data.code === 20000) {
                done()
                HMessage.success('取消完成')
                tagsViewStore.delView(route.path)
                router.push('/return/factory/list')
                return
              }
              HMessageBox.error(res.data.message)
            })
            .finally(() => {
              instance.confirmButtonLoading = false
              instance.cancelButtonLoading = false
            })
          return
        }

        done()
      },
    })
  }
</script>

<template>
  <div class="return-factory-detail-header">
    <div class="title-wrapper">
      <i class="iconfont icon-detail"></i>
      <div class="title">返厂单号：</div>
      <div class="return-factory-code">{{ props.detail.repairNo }}</div>
      <h-status :type="statusTxt.status">{{ statusTxt.txt }}</h-status>
    </div>
    <div class="btn-group">
      <!-- 先隐藏，后面会用到 -->
      <!-- <el-dropdown trigger="click">
        <h-button>
          确认处理方式
          <el-icon>
            <arrow-down></arrow-down>
          </el-icon>
        </h-button>

        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item>退货</el-dropdown-item>
            <el-dropdown-item>换货</el-dropdown-item>
            <el-dropdown-item>生成工单</el-dropdown-item>
            <el-dropdown-item>寄回</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown> -->
      <h-plain-button
        v-if="props.detail.status === 1"
        v-permission="'retrunFactory_check'"
        type="warning"
        @click="onCheck"
      >
        审核
      </h-plain-button>
      <h-plain-button
        v-else-if="props.detail.status === 2 && props.detail.btnEventType === 1"
        v-permission="'retrunFactory_logistics'"
        @click="onFillLogistics"
      >
        填写返厂物流
      </h-plain-button>
      <h-plain-button
        v-else-if="props.detail.status === 3 && props.detail.btnEventType === 2"
        v-permission="'retrunFactory_sign'"
        @click="onSignForReceipt"
      >
        签收设备
      </h-plain-button>
      <h-button v-if="[2, 3].includes(props.detail.status)" @click="onCancelClick">取消</h-button>
      <!-- <h-plain-button
        v-if="props.detail.status === 4 && props.detail.btnEventType === 3"
        v-permission="'retrunFactory_detect'"
        @click="onDetectCreate"
      >
        生成检测单
      </h-plain-button> -->
    </div>

    <!-- 设备审核弹窗 -->
    <check-good-modal
      v-model:visible="goodCheckModalVisible"
      :return-factory-id="props.detail.id"
      :check-method="props.moduleCheckMethod"
      :goods="props.selectedGoods"
      @check-success="emits('update')"
    />

    <!-- 物流填写弹窗 -->
    <logistics-fill-in-modal
      v-model:visible="logisticsFillInModalVisible"
      :check-method="props.moduleCheckMethod"
      :return-factory-id="props.detail.id"
      :selected-logistics-list="props.selectedGoods"
      @update="emits('update')"
    />

    <!-- 签收弹窗 -->
    <sign-for-receipt
      v-model:visible="signForReceiptModalVisible"
      :good-list="props.selectedGoods"
      :return-factory-id="props.detail.id"
      @update="emits('update')"
    />
  </div>
</template>

<style scoped lang="scss">
  .return-factory-detail-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title-wrapper {
      display: flex;
      align-items: center;
      column-gap: 5px;
      font-size: 14px;

      .iconfont {
        color: $primaryColor;
      }

      .title {
        font-weight: bold;
      }
    }

    .btn-group {
      display: flex;
      column-gap: 5px;
    }
  }
</style>
